package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;

import com.cungmua.app.R;
import com.cungmua.app.adapter.PlaceSlidesFragmentAdapter;
import com.cungmua.app.base.BaseDrawerActivitys;
import com.cungmua.app.handler.DealDetailsHandler;
import com.cungmua.app.handler.LikeHandler;
import com.cungmua.app.model.Cart;
import com.cungmua.app.model.DealDetails;
import com.cungmua.app.model.request.DealDetailsRequest;
import com.cungmua.app.model.request.LikeRequest;
import com.cungmua.app.model.response.DealDetailsResponse;
import com.cungmua.app.model.response.LikeResponse;
import com.cungmua.app.task.DealDetailsTask;
import com.cungmua.app.task.LikeTask;
import com.cungmua.app.utils.AppUtils;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TitlePageIndicator;

/**
 * Created by kelvin.nguyen on 6/23/14.
 */
public class DealDetailsActivity extends BaseDrawerActivitys implements DealDetailsHandler,LikeHandler{
    private int currentDealId;
    private ImageView imgImage;
    private Button btnLike;
    private TextView txtTimer;
    private TextView txtMarketPrice;
    private TextView txtPrice;
    private TextView txt_ShortName;
    private TextView txtFullName;
    private TextView txtNumberPeople;
    private TextView txtCall;
    private TextView txt_detailId;
//    private TextView txtNoiBat;
//    private TextView txtNote;
//    private TextView txtChitiet;
//    private TextView txtAddress;
    private ImageButton btnBuy;
    private ViewPager pagerImages;
    private PageIndicator pagerIndicator;
    private ViewPager pagerDealInfo;
    private View viewFooter;
    private TitlePageIndicator pagerTitle;
    private CountDownTimer countDownTimer;
    private DealDetails details;
    private ShareActionProvider shareActionProvider;
    private View frameTime;
    private ImageView icon_home;
    private Button icon_cart;
    private LinearLayout btnCart;
    private LinearLayout btnFeatured;
    private LinearLayout btnNote;
    private LinearLayout btnAddress;
    private LinearLayout btnPromotion;
    private LinearLayout rootNumberPeople;



    @Override
    public int getLayoutResource() {
        return R.layout.activity_deal_details;
    }

    @Override
    public void updateView() {
        DealDetailsRequest request = new DealDetailsRequest(getDeviceId(), getToken());
        request.setCityId(getCurrentCity().getId());
        request.setUserId(getCurrentUser().getId());
        request.setDealId(currentDealId);

        DealDetailsTask task = new DealDetailsTask(this, this);
        task.execute(request);
    }


    @Override
    public void loadControls(Bundle savedInstanceState) {
        currentDealId = getIntent().getExtras().getInt(IK_DEAL_ID);

        frameTime = (View) findViewById(R.id.frameTime);

        btnLike = (Button) findViewById(R.id.btnLike);
        txtTimer = (TextView) findViewById(R.id.txtTimer);
        txtMarketPrice = (TextView) findViewById(R.id.txtMarketPrice);
        txtMarketPrice.setPaintFlags(txtMarketPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        txtPrice = (TextView) findViewById(R.id.txtPrice);
        txt_ShortName = (TextView) findViewById(R.id.txt_ShortName);
        txtFullName = (TextView) findViewById(R.id.txtFullName);
        txtNumberPeople = (TextView) findViewById(R.id.txtNumberPeople);
        txtCall = (TextView) findViewById(R.id.txtCall);
        txt_detailId = (TextView) findViewById(R.id.txt_detailId);
        btnBuy = (ImageButton) findViewById(R.id.btnBuy);
        pagerImages = (ViewPager) findViewById(R.id.pagerImages);
        pagerIndicator = (PageIndicator) findViewById(R.id.pagerIndicator);
        icon_home=(ImageView)findViewById(R.id.icon_home);
        icon_cart=(Button)findViewById(R.id.icon_cart);
        btnCart=(LinearLayout)findViewById(R.id.btnCart);

        btnFeatured=(LinearLayout)findViewById(R.id.btnFeatured);
        btnNote=(LinearLayout)findViewById(R.id.btnNote);
        btnAddress=(LinearLayout)findViewById(R.id.btnAddress);
        btnPromotion=(LinearLayout)findViewById(R.id.btnPromotion);
        rootNumberPeople=(LinearLayout)findViewById(R.id.rootNumberPeople);


        Cart currentCart=getCurrentCart();
        if(currentCart.getTotalQuantity()>0) {
            icon_cart.setText(currentCart.getTotalQuantity() + "");
            icon_cart.setVisibility(View.VISIBLE);
        }else{
            icon_cart.setVisibility(View.GONE);
        }


        icon_home.setOnClickListener(new ImageView.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMenu();
            }
        });

        txtCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToCall(txtCall.getText().toString());
            }
        });

        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToYourCart();
            }
        });

        btnFeatured.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToDealFeatured(currentDealId,KEY_FEATURED);
            }
        });

        btnNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToDealFeatured(currentDealId,KEY_NOTE);
            }
        });

        btnAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToDealMapAddress(currentDealId,KEY_ADDRESS);
            }
        });

        btnPromotion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToDealFeatured(currentDealId,KEY_PROMOTION);
            }
        });



    }
    public void onClick(){
        Toast.makeText(getApplicationContext(),details.getImageList().get(pagerImages.getCurrentItem()) ,Toast.LENGTH_LONG).show();
    }
    @Override
    public void onDealDetails(DealDetailsResponse response) {
        details = response.getData();

        if(details.getMapAddressList()==null)
            btnAddress.setVisibility(View.GONE);

        pagerImages.setAdapter(new PlaceSlidesFragmentAdapter(getSupportFragmentManager(),
                details.getImageList()));

        pagerIndicator.setViewPager(pagerImages);

        String priceString = getString(R.string.full_price_string, AppUtils.getFullPriceString(details.getMarketPrice()));
        txtMarketPrice.setText(priceString);
        priceString = getString(R.string.full_price_string, AppUtils.getFullPriceString(details.getPrice()));
        txtPrice.setText(priceString);

        txt_ShortName.setText(details.getShortName()+"");
        txtFullName.setText(details.getFullName()+"");
        txtNumberPeople.setText(details.getTotalRegistry()+"");
        txt_detailId.setText(details.getId()+"");

        if(details.getTotalRegistry()<1)
            rootNumberPeople.setVisibility(View.GONE);

        if (details.getEndDate() != null) {
            long endTime = details.getEndDate().getTime();
            if (Integer.parseInt(AppUtils.getDayDifference(endTime).trim()) <= 1) {
                txtTimer.setText(AppUtils.getDayDifference(endTime) + getString(R.string.days) + "\n"
                        + AppUtils.getTimeDifference(endTime));
                txtTimer.setVisibility(View.VISIBLE);
                if (countDownTimer != null)
                    countDownTimer.cancel();

                countDownTimer = new CountDownTimer(AppUtils.getMilisDifference(details.getEndDate().getTime()), 1000) {
                    @Override
                    public void onTick(long l) {
                        txtTimer.setText(AppUtils.getDayDifference(details.getEndDate().getTime()) + getString(R.string.days) + "\n"
                                + AppUtils.getTimeDifference(details.getEndDate().getTime()));
                    }

                    @Override
                    public void onFinish() {

                    }
                }.start();
            } else {
                frameTime.setVisibility(View.INVISIBLE);
            }
        } else {
            frameTime.setVisibility(View.INVISIBLE);
            txtTimer.setVisibility(View.INVISIBLE);
        }
            switch (details.getDealStatus()) {
            case DealDetails.ACTIVE:
                btnBuy.setImageResource(R.drawable.selector_button_buy);
                break;
            case DealDetails.COMING_SOON:
                btnBuy.setImageResource(R.drawable.selector_button_coming_soon);
                frameTime.setVisibility(View.INVISIBLE);
                break;
            case DealDetails.SOLD_OUT:
                btnBuy.setImageResource(R.drawable.selector_button_out_of_stock);
                frameTime.setVisibility(View.INVISIBLE);
                break;
            case DealDetails.EXPIRED:
                btnBuy.setImageResource(R.drawable.selector_button_expired);
                break;
            case DealDetails.INACTIVE:
                btnBuy.setImageResource(R.drawable.selector_button_cancelled);
                break;
        }
        if (details.getDealStatus() != DealDetails.ACTIVE)
            btnBuy.setEnabled(false);

        btnLike.setSelected(details.isLiked());

        btnLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getCurrentUser().getId() == 0) {
                    login();
                } else {
                    boolean liked = !btnLike.isSelected();

                    DealDetailsActivity ac = DealDetailsActivity.this;

                    LikeRequest request = new LikeRequest(ac.getDeviceId(), ac.getToken());
                    request.setUserId(ac.getCurrentUser().getId());
                    request.setCityId(ac.getCurrentCity().getId());
                    request.setLiked(liked);
                    request.setDealId(details.getId());

                    LikeTask task = new LikeTask(ac, ac);
                    task.execute(request);
                }
            }
        });

        btnBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToBuy(details);
            }
        });
    }

    @Override
    public void onLiked(LikeResponse response) {
        if (response.getCode() == 0) {
            if (response.isLiked())
                Toast.makeText(this, R.string.liked, Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(this, R.string.disliked, Toast.LENGTH_SHORT).show();

            btnLike.setSelected(response.isLiked());
        } else {
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setMessage(response.getMessage())
                    .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).show();
        }

    }
}
